<?php
/**
 * @author Laurent SITTLER <lolo.sittler@gmail.com>
 * @author Alexandre GOMEZ <gomez.alexandre02@gmail.com>
 * @version 0.1
 */

/**
 * Application Boot
 */
class Bootstrap {

    /**
     * Create Boot
     */
    function __construct() {
        Session::Init();
    }

    /**
     * Load Page
     */
    function Load() {
        $this->m_url = $this->GetCurrentUrl();
        $this->Redirect();
    }

    /**
     * Get current URL
     * @return Current URL
     */
    private function GetCurrentUrl() {
        return explode('/', (rtrim((isset($_GET['url']) ? $_GET['url'] : null), '/')));
    }

    /**
     * Redirect current page controller
     * @return boolean
     */
    function Redirect() {
        // Simple URL
        if (empty($this->m_url[0])) {
            $file = 'Controller/Index.php';
            if (file_exists($file)) {
                require $file;
                $controller = new Index();
                $controller->Update();
                return false;
            } else {
                throw new Exception("Fichier introuvable");
                return false;
            }
        }

        // Check file exist
        $file = 'Controller/' . $this->m_url[0] . '.php';

        if (file_exists($file)) {
            require $file;
        } else {
            throw new Exception("Fichier introuvable");
            return false;
        }


        $controller = new $this->m_url[0];
        $controller->LoadModel($this->m_url[0]);

        if (isset($this->m_url[2])) {
            if (method_exists($controller, $this->m_url[1])) {
                $controller->LoadModel($this->m_url[1]);
                $controller->{$this->m_url[1]}($this->m_url[2]);
            } else {
                throw new Exception("Fichier introuvable");
                return false;
            }
        } else {
            if (isset($this->m_url[1])) {
                if (method_exists($controller, $this->m_url[1])) {
                    $controller->LoadModel($this->m_url[1]);
                    $controller->{$this->m_url[1]}();
                } else {
                    throw new Exception("Fichier introuvable");
                    return false;
                }
            }
        }
        $controller->Update();
    }

    /**
     * Get Url
     * @return Array URL
     */
    public function getUrl() {
        return $this->m_url;
    }

    /**
     *URL
     * @var String 
     */
    private $m_url;

}
